package com.ruoyi.common.utils;

import com.itextpdf.text.pdf.BaseFont;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.*;

public class CreatePDFByHtml {

    public static void main(String[] args) throws IOException {
        String pdfPath = "/Users/xuezhengqin/Desktop/1.pdf";
        //createPDFByHtml(pdfPath);
    }

    /**
     * 该方法用来将指定的word文件转换成pdf文件（使用flying saucer技术）
     *
     * @param pdfPath:生成后的pdf所在目录，包括目录+pdf名称+.+pdf
     * @param htmlStr 转pdf的数据
     * @param fontPath 字体所在路径
     */
    public static boolean createPDFByHtml(String pdfPath, String htmlStr, String fontPath) {
        boolean result = false;
        try {
            OutputStream os = new FileOutputStream(pdfPath);
            ITextRenderer renderer = new ITextRenderer();
            //renderer.getSharedContext().setBaseURL("/Users/xuezhengqin/Desktop");
            // 如果携带图片则加上以下两行代码,将图片标签转换为Itext自己的图片对象，Base64ImgReplacedElementFactory为图片处理类
            //renderer.getSharedContext().setReplacedElementFactory(new Base64ImgReplacedElementFactory());
            //renderer.getSharedContext().getTextRenderer().setSmoothingThreshold(0);
            /*String str = "<body style='font-family:SimSun'><img src='/Users/xuezhengqin/Desktop/tensor.png' style='width:100px' />" +
                    "<div style='color:red;margin-top:30px;'>12你好</div><img src='/Users/xuezhengqin/Desktop/1.png' style='width:100px' /></body>";*/
            Document doc = Jsoup.parse(htmlStr);
            Elements elements = doc.select("img");
            int i = 0;
            for (Element element : elements) {
                element.attr("id", i + "");
                i++;
            }
            String content = doc.html();
            content = content.replace("&nbsp;", "&#160;");
            content = content.replace("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">", "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></meta>");
            content = content.replace("(filtered)\">", "(filtered)\"></meta>");
            content = content.replaceAll("<br>", "<br></br>");
            for (Element element : elements) {
                String startStr = element.outerHtml();
                String endStr = element.outerHtml() + "</img>";
                content = content.replace(startStr, endStr);
            }
            //System.out.println(content);

            renderer.setDocumentFromString(content);

            ITextFontResolver fontResolver = renderer.getFontResolver();

            // fontResolver.addFont("/Users/liqi/ideaWorkspace/java-export-word-plugin-master/PluginExample/src/main/resources/ftl/simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            fontResolver.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

                /*  // mac
                fontResolver.addFont("/library/fonts/Arial Unicode.ttf",
                        BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

                // linux：
                fontResolver.addFont("/usr/share/fonts/TTF/ARIALUNI.TTF",
                        BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

                // windows:
                fontResolver.addFont("C:/Windows/Fonts/ARIALUNI.TTF",
                        BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);   */


            // 解决中文支持问题
                /*fontResolver.addFont("/library/fonts/Arial Unicode.ttf",
                       BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                */
            renderer.layout();
            renderer.createPDF(os);
            os.flush();
            os.close();
            result = true;
        } catch (Exception e) {
            result = false;
            e.printStackTrace();
        }

        return result;
    }

}
